/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        // Time complexity: O(n), n is the number of elements in the list
        // Space complexity: O(n)
        /*if(head == null || head.next == null) {
            return head;
        }
        
        Stack<ListNode> stack = new Stack<>();
        ListNode temp = head;
        while(temp != null) {
            stack.push(temp);
            temp = temp.next;
        }

        ListNode newHead = stack.pop();
        temp = newHead;
        while(!stack.isEmpty()) {
            temp.next = stack.peek();
            temp = stack.pop();
        }

        temp.next = null;

        return newHead;*/

        // Time complexity: O(n)
        // Space complexity: O(1)
        ListNode previous = null, current = head, next;
        while(current != null) {
            next = current.next;
            current.next = previous;
            previous = current;
            current = next;
        } 
        
        return previous;
    }   
}